package org.aeon.colorfulplanebattle.view.components;

import org.aeon.colorfulplanebattle.constant.GameStateE;
import org.aeon.colorfulplanebattle.view.GameState;

import javax.swing.*;
import java.awt.*;
import java.util.Timer;
import java.util.TimerTask;

import static org.aeon.colorfulplanebattle.constant.GameBasisConstant.*;

/**
 * @author: MissingAeon
 * @date: 2024/1/12 11:27
 * @description: 时钟
 */
public class Clock extends JLabel {
    private final GameState gameState;
    private Timer timer;
    private long second = 0;

    public Clock(GameState gameState) {
        this.gameState = gameState;
        this.setBounds((BATTLEFIELD_WIDTH - CLOCK_WIDTH) / 2, 100, CLOCK_WIDTH, CLOCK_HEIGHT);
        this.setForeground(CLOCK_COLOR);
        this.setFont(CLOCK_FONT);
        gameState.put("ClockReset", (Runnable) this::reset);
    }

    private void reset() {
        if (timer != null)
            timer.cancel();
        this.second = 0;
        timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                second++;
            }
        }, 1000, 1000);
    }

    @Override
    protected void paintComponent(Graphics g) {
        if (gameState.getState() == GameStateE.IN_PROGRESS) {
            this.setText(String.format("%02d:%02d:%02d", second / 3600, second % 3600 / 60, second % 60));
            super.paintComponent(g);
        }
    }
}
